package department

import (
	"errors"
	"cgs-server/server/base"
	"cgs-server/server/model"
	"cgs-server/server/system/user"
)

type DepartmentService interface {
	base.Service
}

func NewDepartmentService() DepartmentService {
	deptRepo := NewDepartmentRepository()
	return &departmentService{
		ServiceImpl: base.ServiceImpl{
			Repo: deptRepo,
		},
		deptRepo:    deptRepo,
	}
}

type departmentService struct {
	base.ServiceImpl
	deptRepo DepartmentRepository
}

// 新增部门
func (d *departmentService) Save(mdl *model.DataUserModel) error {
	return d.deptRepo.Insert(mdl)
}

// 修改部门
func (d *departmentService) Update(mdl *model.DataUserModel) error {
	return d.deptRepo.Update(mdl)
}

// 删除部门
func (d *departmentService) Remove(mdl *model.DataUserModel) error {
	// todo 删除子部门
	//TODO check if has users or has sub depts
	// 删除部门
	return d.deptRepo.Delete(mdl)
}

// 获取部门列表
func (d *departmentService)  List(mdl *model.DataUserModel) (interface{}, error) {
	// 1. 查询所有部门（当前租户下）
	deptsRes, err := d.deptRepo.Find(mdl)
	if err != nil {
		return nil, err
	}
	// 2. 查询所有用户（当前租户下）
	duModel := &model.DataUserModel{
		Data: &model.User{},
		User: mdl.User,
	}
	userService := user.NewUserService()
	usersRes, err := userService.List(duModel)
	if err != nil {
		return nil, err
	}
	//fmt.Println(usersRes)
	// 3. 设置部门的管理员字段
	if depts, ok := deptsRes.([]*model.Department); ok {
		if users, ok := usersRes.(model.Users); ok {
			for _, dept := range depts{
				for idx := range users{
					if dept.AdminID == users[idx].UserId.Hex() {
						dept.AdminName = users[idx].Name
					}
				}
			}
			return depts, nil
		} else {
			return nil, errors.New("user type error")
		}
	} else {
		return nil, errors.New("dept type error")
	}
}
